import axios from 'axios'
import store from '@/store'
import { gotoLoginWithRedirect } from '@/router'
import { refreshTokenByShare } from './refreshToken'
import { Message } from 'element-ui'

export const request = axios.create()
request.interceptors.request.use(
  config => {
    if (store.state.user) {
      config.headers.Authorization = store.state.user.access_token
    }
    return config
  }
)
request.interceptors.response.use(resp => resp, async error => {
  if (error.response) {
    // The request was made and the server responded with a status code
    // that falls out of the range of 2xx
    const { status } = error.response
    if (status === 400) {
      Message.error('参数错误')
    } else if (status === 401) {
      if (!store.state.user || error.config.refreshed) {
        gotoLoginWithRedirect()
        return Promise.reject(error)
      } else {
        // refreshToken
        error.config.refreshed = true // 避免循环
        return refreshTokenByShare(store.state.user.refresh_token)
          .then(
            // Suc:重发
            () => request(error.config)
            ,
            // Fail:作为失败
            (e: Error) => {
              gotoLoginWithRedirect()
              return Promise.reject(e)
            }
          )
      }
    } else if (status === 403) {
      Message.error('无权操作')
    } else if (status === 404) {
      Message.error('资源不存在')
    } else if (status >= 500) {
      Message.error('服务端错误,请联系管理员:' + error.message)
    }
  } else if (error.request) {
  // The request was made but no response was received
  // `error.request` is an instance of XMLHttpRequest in the browser and an instance of
  // http.ClientRequest in node.js
    console.log(error.request)
    Message.error('请求超时,请稍后重试:' + error.message)
  } else {
  // Something happened in setting up the request that triggered an Error
    console.log('Error', error.message)
    Message.error('请求失败:' + error.message)
  }
})

// todo 错误处理根据场景分配：通用错误由全局处理负责，剩下的交给局部
